from django_redis import get_redis_connection
from rest_framework import serializers

from apps.users.models import User


class UserInfoSerializer(serializers.Serializer):
    username = serializers.CharField()
    mobile = serializers.RegexField(regex=r'1[3-9]\d{9}')
    email =serializers.EmailField()
    email_active = serializers.BooleanField()

class UserSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(write_only=True)
    sms_code = serializers.CharField(write_only=True)
    allow = serializers.BooleanField(write_only=True)
    class Meta:
        model = User
        fields = ['username', 'password', 'password2', 'mobile', 'sms_code', 'allow']
        extra_kwargs = {
            'username': {'max_length': 20, 'min_length': 5},
            'password': {'write_only': True}
        }

    def validate(self, data):
        mobile = data.get('mobile')
        sms_code = data.get('sms_code')
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        if not sms_code_server:
            raise serializers.ValidationError('验证码已经过期')
        if sms_code_server.decode() != sms_code:
            raise serializers.ValidationError('验证码错误')

        return data

    def create(self, validated_data):
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = User.objects.create_user(**validated_data)

        return user
